package controller

import (
	"html/template"
	"net/http"
	"time"
	"web08_35_tushu/dao"
	"web08_35_tushu/model"
	"web08_35_tushu/utils"
)

//Checkout 保存订单
func Checkout(w http.ResponseWriter, r *http.Request) {
	//获取session方便查购物车
	_, session := dao.IsLogin(r)
	userID := session.UserID
	//查出购物车，直接给订单
	cart, _ := dao.GetCartByUserID(userID)
	//生成订单ID
	orderID := utils.CreateUUID()
	//创建订单，数值基本都是复制
	order := &model.Order{
		OrderID: orderID,
		//.Format("")可以指定返回什么格式的字符串，里面的日期必须写指定的
		CreateTime:  time.Now().Format("2006-01-02 15:04:05"),
		TotalCount:  cart.TotalCount,
		TotalAmount: cart.TotalAmount,
		State:       0,
		UserID:      int64(userID),
	}
	//直接添加
	dao.AddOrder(order)
	//然后就是添加订单项
	cartItems := cart.CartItems
	for _, v := range cartItems {
		orderItem := &model.OrderItem{
			Count:   v.Count,
			Amount:  v.Amount,
			Title:   v.Book.Title,
			Author:  v.Book.Author,
			Price:   v.Book.Price,
			ImgPath: v.Book.ImgPath,
			OrderID: orderID,
		}
		//更新订单项
		dao.AddOrderItem(orderItem)
		//更新下图书库存和销量
		book := v.Book
		book.Sales = book.Sales + int(v.Count)
		book.Stock = book.Stock - int(v.Count)
		dao.UpdateBook(book)

	}
	//添加完后清空购物车
	dao.DeleteCartByCartID(cart.CartID)
	t := template.Must(template.ParseFiles("pages/cart/checkout.html"))
	t.Execute(w, order)
}

//GetOrders 获取所有订单
func GetOrders(w http.ResponseWriter, r *http.Request) {
	orders, _ := dao.GetOrders()
	t := template.Must(template.ParseFiles("pages/order/order_manager.html"))
	t.Execute(w, orders)
}

//GetOrderInfo 获取订单对应的订单项
func GetOrderInfo(w http.ResponseWriter, r *http.Request) {
	//先获取订单号
	orderID := r.FormValue("orderId")
	//根据订单号获取所有订单项
	orderItems, _ := dao.GetOrderItemsByOrderID(orderID)
	t := template.Must(template.ParseFiles("pages/order/order_info.html"))
	t.Execute(w, orderItems)
}

//GetMyOrders 获取指定用户的订单
func GetMyOrders(w http.ResponseWriter, r *http.Request) {
	_, session := dao.IsLogin(r)
	userID := session.UserID
	orders, _ := dao.GetMyOrders(userID)
	t := template.Must(template.ParseFiles("pages/order/order.html"))
	t.Execute(w, orders)
}

//SendOrder 发货
func SendOrder(w http.ResponseWriter, r *http.Request) {
	orderID := r.FormValue("orderId")
	dao.UpdateOrderState(orderID, 1)
	//更新完数据后重定向一下，相当于刷新一下了
	w.Header().Set("Location", "/getOrders")
	w.WriteHeader(302)
}

//TakeOrder 确认收货，点了确认收货就是交易完成，状态码变成2
func TakeOrder(w http.ResponseWriter, r *http.Request) {
	orderID := r.FormValue("orderId")
	dao.UpdateOrderState(orderID, 2)
	//更新完数据后重定向一下，相当于刷新一下了
	w.Header().Set("Location", "/getMyOrders")
	w.WriteHeader(302)
}
